//
//  User.swift
//  Box
//
//  Created by mn on 2025/4/1.
//

import Foundation
import UIKit

struct User: Codable {
    let id: String
    let createTime: Int
    let userNO: Int
    let aliUserId: String?
    let unionId: String?
    let openId: String?
    let sessionKey: String?
    let token: String
    let nickname: String
    let headUrl: String
    let phone: String
    let anchor: Int
    let lastLoginTime: Int
    let redBagTotalAmount: Int
    let availableRedBagCount: Int
    let commission: Int
    let frozenCommission: Int
    let availableCommission: Int
    let alipayAccount: String
    let alipayName: String
    let balance: Int
    let score: Int
    let dragonBall: Int
    let openCount: Int
    let waitPayCount: Int
    let waiSendCount: Int
    let waiAcceptCount: Int
    let finishCount: Int
    let cancelCount: Int
    let needGetPhone: Int
    let agentId: String?
    let agentFlag: String?
    let upId: String?
    let joinCommunity: Bool
    let joinOfficial: Bool
    let joinDiscount: Bool?
    let channel: Int
    let status: Int
    let a_oId: String?
    let giveLimit: Int
    let vip: Int
    let vipAmount: Int
    let vipBuyLimit: Int
}

class UserManager {
    static let shared = UserManager()
    
    private(set) var currentUser: User?
    private let userStorageKey = "loggedInUser"
    
    private init() {
        loadUserFromStorage()
    }
    
    func loadUserFromStorage() {
        if let savedUserData = UserDefaults.standard.data(forKey: userStorageKey),
           let user = try? JSONDecoder().decode(User.self, from: savedUserData) {
            self.currentUser = user
        }
    }
    
    func updateUser(from response: String?) {
        guard let jsonString = response,
              let data = jsonString.data(using: .utf8) else {
            print("Invalid response format: Expected a JSON string")
            return
        }
        
        do {
            // 解析最外层 JSON
            if let outerJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
               let userData = outerJson["data"] as? [String: Any] {
                
                // 解析 User
                let userDataJson = try JSONSerialization.data(withJSONObject: userData, options: [])
                let user = try JSONDecoder().decode(User.self, from: userDataJson)
                
                self.currentUser = user
                if let encodedUser = try? JSONEncoder().encode(user) {
                    UserDefaults.standard.set(encodedUser, forKey: userStorageKey)
                }
            } else {
                print("Failed to extract user data from response")
            }
        } catch {
            print("JSON parsing error: \(error)")
        }
    }
    
    func clearUser() {
        self.currentUser = nil
        UserDefaults.standard.removeObject(forKey: userStorageKey)
    }
    func update( _ complete:( () -> Void)? = nil) {
        APIService.request(api: .getUserInfo) {
            [weak self] (result,response) in
            if result.success{
                complete?()
                self?.updateUser(from: response)
            }else{
                self?.clearUser()
                NotificationCenter.default.post(name: .userDidLogout, object: nil)
            }
        }
    }
    func isLogin() -> Bool{
        currentUser != nil
    }
    
    func pushToLogin(_ viewController: UIViewController?,_ complete:( () -> Void)? = nil){
        let vc = LoginViewController()
        vc.complete = complete
        if let nav = viewController as? UINavigationController{
            nav.push(vc)
        }else{
            viewController?.navigationController?.push(vc)
        }
    }
    
}

extension Notification.Name {
    static let userDidLogout = Notification.Name("UserDidLogoutNotification")
}
